import { Injectable } from '@angular/core';
import { Headers, Http,Jsonp,URLSearchParams} from '@angular/http';
import { Observable } from 'rxjs/Observable';

import * as moment from 'moment';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class UtilService {

  constructor(
    public http: Http,
    public _jsonp:Jsonp
  ) { }

  public get(url: string): Promise<any> {
    return this.http
      .get(url)
      .toPromise()
      .then(response => response)
      .catch(this.handleError);
  }
  public jsonp(url: string){
    var params = new URLSearchParams();
    //jsonp必须要有此参数 以及‘JSONP_CALLBACK’值
    params.set('callback', 'JSONP_CALLBACK');
    params.set("type","jsonp");
    //时间戳防缓存
    params.set("_",(new Date()).valueOf().toString());
    return this._jsonp
      .get(url, {search: params})
      .map(res=> res.json())
  }
  public post(url: string, data: any): Promise<any> {
    let headers = new  Headers({ 'Accept': 'application/json', 'Content-Type': 'application/json' ,'charset':'utf-8'});
    return this.http
      .post(url, JSON.stringify(data),{ headers: headers })
      .toPromise()
      .then(response => response)
      .catch(this.handleError);
  }

  public create(url: string, data: any): Promise<any> {
    return this.http
      .post(url, JSON.stringify(data))
      .toPromise()
      .then(res => res.json())
      .catch(this.handleError);
  }

  public delete(url: string): Promise<any> {
    return this.http
      .delete(url)
      .toPromise()
      .then(res => res.json())
      .catch(this.handleError);
  }

  public update(url: string, data: any): Promise<any> {
    return this.http
      .put(url, JSON.stringify(data))
      .toPromise()
      .then(res => res.json())
      .catch(this.handleError);
  }

  public updates(url: string, data: Array<any>): Promise<any> {
    return this.http
      .put(url, JSON.stringify(data))
      .toPromise()
      .then(res => res.json())
      .catch(this.handleError);
  }
  private handleError(error: any): Promise<any> {
    //console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
}
